package com.zenithmind.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zenithmind.common.result.PageResult;
import com.zenithmind.mall.mapper.ProductMapper;
import com.zenithmind.mall.mapper.ProductStockMapper;
import com.zenithmind.mall.mapper.ProductStatisticsMapper;
import com.zenithmind.mall.mapper.ProductSeoMapper;
import com.zenithmind.mall.pojo.entity.Product;
import com.zenithmind.mall.pojo.entity.ProductStock;
import com.zenithmind.mall.pojo.entity.ProductStatistics;
import com.zenithmind.mall.pojo.entity.ProductSeo;
import com.zenithmind.mall.pojo.query.ProductQuery;
import com.zenithmind.mall.pojo.vo.ProductVO;
import com.zenithmind.mall.service.ProductQueryService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品查询服务实现类 - 遵循单一职责原则，专门负责商品的查询操作
 * 
 * @author ZenithMind Team
 * @since 2025-07-03
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ProductQueryServiceImpl implements ProductQueryService {

    private final ProductMapper productMapper;
    private final ProductStockMapper productStockMapper;
    private final ProductStatisticsMapper productStatisticsMapper;
    private final ProductSeoMapper productSeoMapper;

    @Override
    public PageResult<ProductVO> getProductPage(ProductQuery query) {
        Page<Product> page = new Page<>(query.getCurrent(), query.getSize());
        
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Product::getIsDeleted, 0)
               .like(StringUtils.hasText(query.getName()), Product::getName, query.getName())
               .eq(StringUtils.hasText(query.getCategoryId()), Product::getCategoryId, query.getCategoryId())
               .eq(StringUtils.hasText(query.getBrand()), Product::getBrand, query.getBrand())
               .eq(query.getStatus() != null, Product::getStatus, query.getStatus())
               .ge(query.getMinPrice() != null, Product::getPrice, query.getMinPrice())
               .le(query.getMaxPrice() != null, Product::getPrice, query.getMaxPrice())
               .orderByDesc(Product::getCreateTime);

        Page<Product> result = productMapper.selectPage(page, wrapper);
        
        List<ProductVO> voList = result.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());

        return new PageResult<>(voList, result.getTotal(), result.getCurrent(), result.getSize());
    }

    @Override
    public ProductVO getProductById(String id) {
        Product product = productMapper.selectById(id);
        if (product == null) {
            return null;
        }
        return convertToVO(product);
    }

    @Override
    public List<ProductVO> getRecommendProducts(Integer limit) {
        // 查询推荐商品的统计信息
        LambdaQueryWrapper<ProductStatistics> statsWrapper = new LambdaQueryWrapper<>();
        statsWrapper.eq(ProductStatistics::getIsDeleted, 0)
                   .eq(ProductStatistics::getIsRecommend, 1)
                   .orderByDesc(ProductStatistics::getSalesCount)
                   .last("LIMIT " + (limit != null ? limit : 10));
        
        List<ProductStatistics> statsList = productStatisticsMapper.selectList(statsWrapper);
        
        return statsList.stream()
                .map(stats -> {
                    Product product = productMapper.selectById(stats.getProductId());
                    return product != null && product.isOnSale() ? convertToVO(product) : null;
                })
                .filter(vo -> vo != null)
                .collect(Collectors.toList());
    }

    @Override
    public List<ProductVO> getHotProducts(Integer limit) {
        LambdaQueryWrapper<ProductStatistics> statsWrapper = new LambdaQueryWrapper<>();
        statsWrapper.eq(ProductStatistics::getIsDeleted, 0)
                   .eq(ProductStatistics::getIsHot, 1)
                   .orderByDesc(ProductStatistics::getSalesCount)
                   .last("LIMIT " + (limit != null ? limit : 10));
        
        List<ProductStatistics> statsList = productStatisticsMapper.selectList(statsWrapper);
        
        return statsList.stream()
                .map(stats -> {
                    Product product = productMapper.selectById(stats.getProductId());
                    return product != null && product.isOnSale() ? convertToVO(product) : null;
                })
                .filter(vo -> vo != null)
                .collect(Collectors.toList());
    }

    @Override
    public List<ProductVO> getNewProducts(Integer limit) {
        LambdaQueryWrapper<ProductStatistics> statsWrapper = new LambdaQueryWrapper<>();
        statsWrapper.eq(ProductStatistics::getIsDeleted, 0)
                   .eq(ProductStatistics::getIsNew, 1)
                   .orderByDesc(ProductStatistics::getCreateTime)
                   .last("LIMIT " + (limit != null ? limit : 10));
        
        List<ProductStatistics> statsList = productStatisticsMapper.selectList(statsWrapper);
        
        return statsList.stream()
                .map(stats -> {
                    Product product = productMapper.selectById(stats.getProductId());
                    return product != null && product.isOnSale() ? convertToVO(product) : null;
                })
                .filter(vo -> vo != null)
                .collect(Collectors.toList());
    }

    @Override
    public List<ProductVO> getProductsByCategory(String categoryId, Integer limit) {
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Product::getIsDeleted, 0)
               .eq(Product::getCategoryId, categoryId)
               .eq(Product::getStatus, 1) // 上架状态
               .orderByDesc(Product::getCreateTime)
               .last("LIMIT " + (limit != null ? limit : 10));
        
        List<Product> products = productMapper.selectList(wrapper);
        
        return products.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public List<ProductVO> getProductsByBrand(String brand, Integer limit) {
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Product::getIsDeleted, 0)
               .eq(Product::getBrand, brand)
               .eq(Product::getStatus, 1) // 上架状态
               .orderByDesc(Product::getCreateTime)
               .last("LIMIT " + (limit != null ? limit : 10));
        
        List<Product> products = productMapper.selectList(wrapper);
        
        return products.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public PageResult<ProductVO> searchProducts(String keyword, Integer pageNum, Integer pageSize) {
        Page<Product> page = new Page<>(pageNum, pageSize);
        
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Product::getIsDeleted, 0)
               .eq(Product::getStatus, 1) // 上架状态
               .and(w -> w.like(Product::getName, keyword)
                         .or().like(Product::getDescription, keyword)
                         .or().like(Product::getBrand, keyword))
               .orderByDesc(Product::getCreateTime);

        Page<Product> result = productMapper.selectPage(page, wrapper);
        
        List<ProductVO> voList = result.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());

        return new PageResult<>(voList, result.getTotal(), result.getCurrent(), result.getSize());
    }

    @Override
    public List<ProductVO> getRelatedProducts(String productId, Integer limit) {
        Product product = productMapper.selectById(productId);
        if (product == null) {
            return List.of();
        }
        
        // 查询同分类的其他商品
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Product::getIsDeleted, 0)
               .eq(Product::getCategoryId, product.getCategoryId())
               .eq(Product::getStatus, 1) // 上架状态
               .ne(Product::getId, productId) // 排除当前商品
               .orderByDesc(Product::getCreateTime)
               .last("LIMIT " + (limit != null ? limit : 10));
        
        List<Product> products = productMapper.selectList(wrapper);
        
        return products.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public List<ProductVO> getUserViewedProducts(String userId, Integer limit) {
        // 这里需要从用户浏览记录表中查询，暂时返回热门商品
        return getHotProducts(limit);
    }

    /**
     * 转换为VO
     */
    private ProductVO convertToVO(Product product) {
        ProductVO vo = new ProductVO();
        BeanUtils.copyProperties(product, vo);
        
        // 设置状态名称
        vo.setStatusName(getStatusName(product.getStatus()));
        
        // 获取库存信息
        ProductStock stock = productStockMapper.selectById(product.getId());
        if (stock != null) {
            vo.setStock(stock.getAvailableStock());
            vo.setLowStock(stock.getLowStock());
            vo.setNeedsStockAlert(stock.needsStockAlert());
        }
        
        // 获取统计信息
        ProductStatistics statistics = productStatisticsMapper.selectById(product.getId());
        if (statistics != null) {
            vo.setSalesCount(statistics.getSalesCount());
            vo.setViewCount(statistics.getViewCount());
            vo.setFavoriteCount(statistics.getFavoriteCount());
            vo.setReviewCount(statistics.getReviewCount());
            vo.setAverageRating(statistics.getAverageRating());
            vo.setIsRecommend(statistics.isRecommendProduct() ? 1 : 0);
            vo.setIsNew(statistics.isNewProduct() ? 1 : 0);
            vo.setIsHot(statistics.isHotProduct() ? 1 : 0);
        }
        
        // 获取SEO信息
        ProductSeo seo = productSeoMapper.selectById(product.getId());
        if (seo != null) {
            vo.setKeywords(seo.getKeywords());
            vo.setSeoDescription(seo.getSeoDescription());
            vo.setPageUrl(seo.getPageUrl());
        }
        
        return vo;
    }

    private String getStatusName(Integer status) {
        if (status == null) return "未知";
        switch (status) {
            case 0: return "下架";
            case 1: return "上架";
            case 2: return "预售";
            default: return "未知";
        }
    }
}
